from flask import Flask, make_response, current_app
from flask_restful import Resource, Api
from flask_restful.utils import PY3
from flask_restful.representations import json
import json

app = Flask(__name__)
api = Api(app)

# 原生的做法
# @app.after_request
# def after_request(response):
#     data = json.loads(response.data)
#     if 'message' not in data:
#         new_data = {
#             'message':' OK',
#             'data': data
#         }
#         response.data = json.dumps(new_data)
#     return response
# 需求：{"name": "laowang"} -> {"message": "ok", "data": {"name": "laowang"}}
# @app.route('/')
# def index():
#     data ={
#         'message': 'nihao',
#         'name': 'laowang'
#     }
#     return json.dumps(data)

# 普通做法
# @api.representation('application/json')
# def representation(data, code, headers):
#     if 'message'not in data:
#         data = {
#             'message': 'ok',
#             'data': data
#         }
#     response = make_response(json.dumps(data))
#     response.status_code = code
#     response.headers.extend(headers)
#     return response

# 建议的做法
@api.representation('application/json')
def output_json(data, code, headers=None):
    # 一般不到其他代码,只添加自己的逻辑代码
    if 'message' not in data:
        data = {
            'message': 'OK',
            'data':data
        }
    settings = current_app.config.get('RESTFUL_JSON', {})
    if current_app.debug:
        settings.setdefault('indent', 4)
        settings.setdefault('sort_keys', not PY3)
    dumped = json.dumps(data, **settings)+"\n"
    resp = make_response(dumped, code)
    resp.headers.extend(headers or {})
    return resp


class Index(Resource):
    def get(self):
        return {'name': 'laowang'}


api.add_resource(Index, '/')

if __name__ == "__main__":
    app.run(debug=True,host='0.0.0.0', port=5000)
